﻿using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using System.Web.Http.SelfHost;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using Ubiety.Dns.Core;

namespace CloudApiServer.Services
{
    /// <summary>
    /// HTTP service
    /// </summary>
    public class HttpService : IDisposable
    {
        /// <summary>
        /// HTTP server's listening port.
        /// </summary>
        public int Port { get; set; }

        /// <summary>
        /// HTTP self hosting.
        /// </summary>
        private readonly HttpSelfHostServer _server;

        /// <summary>
        /// HTTP server.
        /// </summary>
        /// <param name="port">Listening port.</param>
        public HttpService(int port)
        {
            this.Port = port;
           

            var config = new HttpSelfHostConfiguration($"http://0.0.0.0:{this.Port}");
            //定义接口最大入参值 最大入参50M
            config.MaxBufferSize = 50 * 1024 * 1024;  
            config.MaxReceivedMessageSize = 50 * 1024 * 1024; 

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}");
            //医保挡板 河北医保接口重定向浙江接口
            config.Routes.MapHttpRoute(name: "CatchAll-fsi-hebei", routeTemplate: "ebus/rio_fsi/{*catchall}", defaults: new { controller = "FsiApiZheJiang" });
            //医保挡板 没被定义的接口
            config.Routes.MapHttpRoute(name: "CatchAll-fsi", routeTemplate: "fsi/api/{*catchall}", defaults: new { controller = "FsiApiZheJiang", action = "FsiNotFound" });
            //医保挡板-异地 没被定义的接口
            config.Routes.MapHttpRoute(name: "CatchAll-fsicts", routeTemplate: "srs/cts-int/api/{*catchall}", defaults: new { controller = "FsiApiZheJiangCtsApi", action = "FsiNotFound" });
            //医保挡板-异地 没被定义的接口
            config.Routes.MapHttpRoute(name: "CatchAll-fsihsaimssvc", routeTemplate: "hsa-ims-svc/api/{*catchall}", defaults: new { controller = "FsiApiZheJiangHsaImsSvc", action = "FsiNotFound" });

            //医保挡板-甘肃接口 没被定义的接口
            config.Routes.MapHttpRoute(name: "CatchAll-fsi-gansu", routeTemplate: "prd/hsa/hgs/{*catchall}", defaults: new { controller = "FsiApiGanSu", action = "FsiNotFound" });
            //医保挡板-湖南接口 没被定义的接口
            config.Routes.MapHttpRoute(name: "CatchAll-fsi-hunan", routeTemplate: "isp-api/{*catchall}", defaults: new { controller = "FsiApiHuNan", action = "FsiNotFound" });
            //医保挡板-安徽接口 重定向到指定路径 
            config.Routes.MapHttpRoute(name: "CatchAll-fsi-anhui-all", routeTemplate: "1.0.0", defaults: new { controller = "FsiApiAnHui", action = "Fsi_Anhui" });
            //医保挡板-安徽接口 智能监管接口回调3101
            config.Routes.MapHttpRoute(name: "CatchAll-fsi-anhui-3101", routeTemplate: "1.0.0/hsa-fsi-3101", defaults: new { controller = "FsiApiAnHui", action = "Fsi_Anhui_RiskConServicen" });
            //医保挡板-安徽接口 智能监管接口回调3102
            config.Routes.MapHttpRoute(name: "CatchAll-fsi-anhui-3102", routeTemplate: "1.0.0/hsa-fsi-3102", defaults: new { controller = "FsiApiAnHui", action = "Fsi_Anhui_RiskConServicen" });
            //医保挡板-安徽接口 没被定义的接口
            config.Routes.MapHttpRoute(name: "CatchAll-fsi-anhui", routeTemplate: "1.0.0/{*catchall}", defaults: new { controller = "FsiApiAnHui", action = "FsiNotFound" });
            //医保挡板-江苏&江西 没被定义的接口
            config.Routes.MapHttpRoute(name: "CatchAll-fsi-jiangsujiangxi", routeTemplate: "CSB/{*catchall}", defaults: new { controller = "FsiApiJiangsuJiangxi", action = "FsiNotFound" });
            //医保挡板-处方中心 没被定义的接口
            config.Routes.MapHttpRoute(name: "CatchAll-fsi-FsiEpc", routeTemplate: "epc/api/{*catchall}", defaults: new { controller = "FsiEpc", action = "FsiNotFound" });
            //医保挡板-山东进销存接口 没被定义的接口
            config.Routes.MapHttpRoute(name: "CatchAll-fsi-ShandongJxc", routeTemplate: "hsu/mihs/{*catchall}", defaults: new { controller = "FsiApiShandongJxc", action = "FsiNotFound" });
            //东软三方 没被定义的接口
            config.Routes.MapHttpRoute(name: "CatchAll-NeusJiangsu", routeTemplate: "public/{*catchall}", defaults: new { controller = "FsiApiNeusJiangsu", action = "NeusJiangsuNotFound" });

           

            //所有api路径未被定义的接口都走NotFound
            config.Routes.MapHttpRoute(name: "CatchAll",routeTemplate: "{*catchall}",defaults: new { controller = "Error", action = "NotFound" });
            config.MessageHandlers.Add(new CustomHeadersHandler());
            _server = new HttpSelfHostServer(config);


        }
        #region HTTP Service

        /// <summary>
        /// start HTTP server.
        /// </summary>
        public Task StartHttpServer()
        {
            return _server.OpenAsync();
        }

        /// <summary>
        /// Close HTTP server.
        /// </summary>
        public Task CloseHttpServer()
        {
            return _server.CloseAsync();
        }

        #endregion

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            _server?.Dispose();
        }
        //public class CustomHeadersHandler : DelegatingHandler
        //{
        //    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        //    {
        //        // 发送请求并获取响应  
        //        var response = await base.SendAsync(request, cancellationToken);

        //        // 记录请求信息  
        //        Console.WriteLine(DateTime.Now + "|" + request.Method + ";url:" + request.RequestUri);
        //        var requestContent = await request.Content.ReadAsStringAsync();
        //        Console.WriteLine(DateTime.Now + "|Input:" + requestContent);
        //        LogHelper.Info("Method:" + request.Method + ";url:" + request.RequestUri);
        //        LogHelper.Info("Input:" + requestContent);

        //        // 处理预请求
        //        if (request.Method == HttpMethod.Options)
        //        {
        //            response.EnsureSuccessStatusCode();
        //            response.StatusCode = HttpStatusCode.OK;
        //            response.Headers.Add("Access-Control-Allow-Origin", "*");
        //            response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        //            response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
        //        }
        //        else
        //        {
        //            //response.EnsureSuccessStatusCode();
        //            response.Headers.Add("Access-Control-Allow-Origin", "*");

        //            // 记录响应信息  
        //            if (response.Content != null)
        //            {
        //                using (var responseStream = await response.Content.ReadAsStreamAsync())
        //                using (var memoryStream = new MemoryStream())
        //                {
        //                    await responseStream.CopyToAsync(memoryStream);
        //                    memoryStream.Position = 0;
        //                    using (var reader = new StreamReader(memoryStream))
        //                    {
        //                        var responseBody = await reader.ReadToEndAsync();
        //                        Console.WriteLine(DateTime.Now + "|Output:" + responseBody);
        //                        LogHelper.Info("Output:" + responseBody);
        //                    }
        //                }
        //            }
        //        }
        //        return response;
        //    }
        //}
        public class CustomHeadersHandler : DelegatingHandler
        {
            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                return base.SendAsync(request, cancellationToken).ContinueWith(task =>
                {
                    LogHelper.Info($"----------请求记录开始----------");
                    // 捕捉并记录请求头
                    foreach (var header in request.Headers)
                    {
                        Console.WriteLine($"{DateTime.Now} | Header: {header.Key} = {string.Join(", ", header.Value)}");
                        LogHelper.Info($"Header: {header.Key} = {string.Join(", ", header.Value)}");
                    }

                    Console.WriteLine($"{DateTime.Now} | {request.Method} {request.RequestUri}");
                    LogHelper.Info("Method:" + request.Method.ToString() + ";url:" + request.RequestUri.ToString());

                    if (!request.RequestUri.ToString().Contains("api/file"))
                    {
                        Console.WriteLine($"{DateTime.Now} | Input: {request.Content.ReadAsStringAsync().Result}");
                        LogHelper.Info("Input:" + request.Content.ReadAsStringAsync().Result);
                    }

                    LogHelper.Info($"----------请求记录结束----------");
                    //处理预请求
                    if (request.Method == HttpMethod.Options)
                    {
                        var response = new HttpResponseMessage(HttpStatusCode.OK);
                        response.Headers.Add("Access-Control-Allow-Origin", "*");
                        response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                        response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
                        Console.WriteLine(response);

                        return response;
                    }
                    else
                    {
                        var response = task.Result;
                        if (response.IsSuccessStatusCode)
                        {
                            response.Headers.Add("Access-Control-Allow-Origin", "*");
                        }
                        Console.WriteLine(response);
                        return response;
                    }
                });
            }
        }
    }
}
